<template>
	<view class="page-container pb-160">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="检验标准详情" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>
		<view class="w-710 mgt bgff pl-32 pr-32 br-20">
			<view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
				<view>监测年份：</view>
				<input class="trt fs-28" placeholder="请输入" v-model="detail.year" :disabled="!showDeleteButton" />
			</view>
			<view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
				<view>监测类别:</view>
				<view class="rows rowsm" @click="showDeleteButton && (showCategoryPicker = true)" 
					:class="{ 'disabled': !showDeleteButton }">
					<view class="fs-28 trt" :class="detail.detectionType ? 'col333' : 'col999'">
						{{ getDetectionTypeLabel(detail.detectionType) || '请选择监测类别' }}
					</view>
					<u-icon v-if="showDeleteButton" name="arrow-down" size="16" color="#999" class="ml-10"></u-icon>
				</view>
			</view>
		</view>
		<!-- 检测标准列表 -->
		<view class="w-710 mgt pl-32 pr-32 br-20">
			<view class="">
				检验方法和依据
			</view>
		</view>
		<view v-if="items.length > 0" class="w-710 mgt bgff pl-20 pr-20 br-20 pt-24 pb-24">
			<!-- 遍历每个产品 -->
			<view v-for="(productName, index) in productNames" :key="index" class="product-section">
				<view class="rowsb rowsm">
					<view class="rows rowsm">
						<image src="/static/icon_bl.png" class="w-40 h-40 mr-20" mode="aspectFill"></image>
						<view class="">{{ productName }}</view>
					</view>
					<view class="rowsc rowsm br-32 w-84 h-48" style="background-color: #FF8C34;color: #fff;"
						@click="addItem(productName)">{{ showDeleteButton ? '添加' : '详情' }}</view>
				</view>

				<!-- 遍历该产品的检测项目 -->
				<view v-for="(item, itemIndex) in groupedItems[productName]" :key="itemIndex"
					class="w-670 pl-24 pr-24 pt-24 mgt" style="background: #F7F7F7;">
					<view class="fs-28 fw-b rowsb rowsm pb-16">
						<view class="rows rowsm">
							<text class="mr-10">{{ item.serialNumber }}.检测项目:</text>
							<input class="fs-28 fw-b" v-model="item.inspectionItem" :disabled="!showDeleteButton"
								placeholder="请输入检测项目" />
						</view>
						<!-- 删除按钮 - 只在编辑模式下显示 -->
						<image v-if="showDeleteButton" src="/static/icon_s.png" class="w-32 h-32 mr-20"
							mode="aspectFill" @click="deleteItem(item, itemIndex)"></image>
					</view>
					<view class="rows rowsm pb-16">
						<view class="col888 fs-26 fw-500 mr-10">限量值(mg/kg):</view>
						<input class="fs-26 fw-500" v-model="item.limitValue" :disabled="!showDeleteButton"
							placeholder="请输入限量值" />
					</view>
					<view class="rows rowsm pb-16">
						<view class="col888 fs-26 fw-500 mr-10">执法依据:</view>
						<input class="fs-26 fw-500" v-model="item.executionBasis" :disabled="!showDeleteButton"
							placeholder="请输入执法依据" />
					</view>
					<view class="rows rowsm pb-16">
						<view class="col888 fs-26 fw-500 mr-10">检测方法:</view>
						<input class="fs-26 fw-500" v-model="item.detectionMethod" :disabled="!showDeleteButton"
							placeholder="请输入检测方法" />
					</view>
				</view>
			</view>
		</view>

		<!-- 无数据提示 -->
		<view v-else-if="pageReady" class="w-710 mgt bgff pl-20 pr-20 br-20 pt-24 pb-24 text-center">
			<text class="col999 fs-28">暂无检测标准数据</text>
		</view>
		<!-- 底部按钮 -->
		<view @tap="submit()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
			style="bottom: 68rpx;left: 30rpx;" v-if="showDeleteButton">
			确认修改
		</view>
		<!-- 监测类别选择器 -->
		<u-picker :show="showCategoryPicker" :columns="[categoryOptions]" @confirm="onCategoryConfirm"
			@cancel="showCategoryPicker = false" title="选择监测类别"></u-picker>
	</view>
</template>

<script>
import { getProductStandard, updateProductStandard } from '@/api/productStandard'
import request from '@/utils/request'
export default {
	data() {
		return {
			pageReady: false,
			detail: {},
			items: [],
			firstProductName: '',
			tabName: 'workbench',
			showDeleteButton: false, // 控制删除按钮显示
			// 监测类别选择器相关
			showCategoryPicker: false,
			categoryOptions: [],
			detectionTypeMap: {},
			detectionTypeDictType: 'product_monitor_type'
		}
	},
	onLoad(options) {
		const id = options && options.id ? options.id : ''
		// 根据来源页面控制删除按钮显示
		this.showDeleteButton = options && options.mode === 'edit'
		
		// 加载监测类别字典
		this.loadDetectionDict()
		
		if (!id) {
			this.pageReady = true
			return
		}
		this.loadDetail(id)
	},
	computed: {
		navbarHeight() {
			// 如果设置了自定义高度，则使用自定义高度
			if (this.customNavbarHeight) {
				return this.customNavbarHeight;
			}
			// 否则自动计算：状态栏高度 + 导航栏高度
			const systemInfo = uni.getSystemInfoSync();
			// 将px转换为rpx (1px = 2rpx)
			const statusBarHeightRpx = systemInfo.statusBarHeight * 2;
			const navbarHeightRpx = 44 * 2; // 44px = 88rpx
			return statusBarHeightRpx + navbarHeightRpx;
		},
		// 按产品分组检测标准数据
		groupedItems() {
			const groups = {}
			this.items.forEach(item => {
				const productName = item.productName || item.product || '未知产品'
				if (!groups[productName]) {
					groups[productName] = []
				}
				groups[productName].push(item)
			})
			return groups
		},
		// 获取所有产品名称
		productNames() {
			return Object.keys(this.groupedItems)
		}
	},
	methods: {
		loadDetail(id) {
			getProductStandard(id).then(res => {
				console.log('详情', res)
				// 兼容不同返回结构
				const data = res?.data || res
				this.detail = data || {}
				
				// 详情页数据存储在 ext1 字段中
				let parsed = []
				const ext1 = data?.ext1
				if (typeof ext1 === 'string' && ext1.trim()) {
					try { 
						parsed = JSON.parse(ext1) 
					} catch (e) { 
						console.error('解析ext1失败:', e)
						parsed = [] 
					}
				}
				
				// 如果 ext1 没有数据，尝试解析 tableData（PC版格式）
				if (!parsed.length) {
					const td = data?.tableData
					if (Array.isArray(td)) {
						parsed = td
					} else if (typeof td === 'string' && td.trim()) {
						try { 
							const tableData = JSON.parse(td)
							// 将PC版格式转换为移动端格式
							parsed = tableData.map(item => ({
								productStandardDetailId: item.productStandardDetailId,
								productId: item.productId,
								productName: item.product,
								product: item.product,
								serialNumber: item.index,
								inspectionItem: item.item,
								limitValue: item.limit,
								executionBasis: item.basis,
								detectionMethod: item.method
							}))
						} catch (e) { 
							console.error('解析tableData失败:', e)
							parsed = [] 
						}
					}
				}
				
				// 最后回退到 rows/detailList
				if (!parsed.length) {
					parsed = Array.isArray(data?.detailList) ? data.detailList : (Array.isArray(res?.rows) ? res.rows : [])
				}
				
				this.items = parsed
				this.firstProductName = parsed?.[0]?.product || parsed?.[0]?.productName || ''
				this.pageReady = true
			}).catch(err => {
				console.error('加载详情失败:', err)
				this.pageReady = true
			})
		},
		// 删除检测项目
		deleteItem(item, itemIndex) {
			uni.showModal({
				title: '提示',
				content: '确定删除该检测项目吗？',
				success: (res) => {
					if (res.confirm) {
						// 从当前分组中删除
						const productName = item.productName || item.product || '未知产品'
						if (this.groupedItems[productName]) {
							this.groupedItems[productName].splice(itemIndex, 1)
							// 重新构建items数组
							this.rebuildItems()
						}
						uni.showToast({ title: '删除成功', icon: 'success' })
					}
				}
			})
		},
		// 重新构建items数组
		rebuildItems() {
			const newItems = []
			Object.keys(this.groupedItems).forEach(productName => {
				newItems.push(...this.groupedItems[productName])
			})
			this.items = newItems
		},
		// 添加检测项目
		addItem(productName) {
			if (this.showDeleteButton) {
				// 编辑模式：在当前产品分组下添加空的检测项目
				const newItem = {
					serialNumber: this.getNextSerialNumber(productName),
					inspectionItem: '',
					limitValue: '',
					executionBasis: '',
					detectionMethod: '',
					productName: productName,
					product: productName,
					isNew: true // 标记为新添加的项目
				}
				
				// 添加到对应产品分组
				if (!this.groupedItems[productName]) {
					this.$set(this.groupedItems, productName, [])
				}
				this.groupedItems[productName].push(newItem)
				
				// 重新构建items数组
				this.rebuildItems()
				
				uni.showToast({
					title: '已添加新检测项目',
					icon: 'success'
				})
			} else {
				// 只读模式：显示详情提示
				uni.showToast({
					title: '当前为只读模式',
					icon: 'none'
				})
			}
		},
		// 获取下一个序号
		getNextSerialNumber(productName) {
			const items = this.groupedItems[productName] || []
			if (items.length === 0) return 1
			
			// 找到最大序号
			let maxNumber = 0
			items.forEach(item => {
				const num = parseInt(item.serialNumber) || 0
				if (num > maxNumber) {
					maxNumber = num
				}
			})
			return maxNumber + 1
		},
		// 加载监测类别字典
		async loadDetectionDict() {
			try {
				const res = await request({ url: `/system/dict/data/type/${this.detectionTypeDictType}`, method: 'get' })
				const rows = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : [])
				const map = {}
				const options = []
				
				rows.forEach(d => {
					const label = d.dictLabel ?? d.label ?? d.name
					const value = d.dictValue ?? d.value ?? d.code
					if (value != null) {
						map[value] = label || value
						options.push(label || value)
					}
				})
				
				this.detectionTypeMap = map
				this.categoryOptions = options
			} catch (e) {
				console.error('加载监测类别字典失败:', e)
				this.detectionTypeMap = {}
				this.categoryOptions = []
			}
		},
		// 监测类别选择确认
		onCategoryConfirm(e) {
			const selectedLabel = e.value[0]
			// 通过标签找到对应的值
			let selectedValue = selectedLabel
			for (const [value, label] of Object.entries(this.detectionTypeMap)) {
				if (label === selectedLabel) {
					selectedValue = value
					break
				}
			}
			this.detail.detectionType = selectedValue
			this.showCategoryPicker = false
		},
		// 获取监测类别标签
		getDetectionTypeLabel(value) {
			if (!value) return ''
			// 如果已经是标签，直接返回
			if (this.categoryOptions.includes(value)) {
				return value
			}
			// 如果是值，通过映射获取标签
			return this.detectionTypeMap[value] || value
		},
		// 提交修改
		async submit() {
			try {
				// 验证必填字段
				if (!this.detail.year) {
					uni.showToast({ title: '请输入监测年份', icon: 'none' })
					return
				}
				if (!this.detail.detectionType) {
					uni.showToast({ title: '请选择监测类别', icon: 'none' })
					return
				}
				
				// 验证检测项目数据
				if (this.items.length === 0) {
					uni.showToast({ title: '请添加检测标准数据', icon: 'none' })
					return
				}
				
				// 验证每个检测项目的必填字段
				for (let i = 0; i < this.items.length; i++) {
					const item = this.items[i]
					if (!item.inspectionItem) {
						uni.showToast({ title: `第${i + 1}项检测项目不能为空`, icon: 'none' })
						return
					}
					if (!item.limitValue) {
						uni.showToast({ title: `第${i + 1}项限量值不能为空`, icon: 'none' })
						return
					}
					if (!item.executionBasis) {
						uni.showToast({ title: `第${i + 1}项执法依据不能为空`, icon: 'none' })
						return
					}
					if (!item.detectionMethod) {
						uni.showToast({ title: `第${i + 1}项检测方法不能为空`, icon: 'none' })
						return
					}
				}
				
				// 显示加载提示
				uni.showLoading({ title: '保存中...' })
				
				// 准备提交数据，参考PC版的数据结构
				const submitData = {
					...this.detail,
					// 将检测标准数据转换为PC版格式
					tableData: JSON.stringify(this.items.map(item => ({
						productStandardDetailId: item.productStandardDetailId || Date.now() + Math.random(),
						productId: item.productId || null,
						product: item.productName || item.product || '',
						index: item.serialNumber || 1,
						item: item.inspectionItem || '',
						limit: item.limitValue || '',
						basis: item.executionBasis || '',
						method: item.detectionMethod || '',
						action: 'delete' // 默认标记为可删除
					}))),
					// 确保ext1字段也包含数据（兼容性）
					ext1: JSON.stringify(this.items)
				}
				
				// 调用修改接口
				await updateProductStandard(submitData)
				
				uni.hideLoading()
				uni.showToast({ 
					title: '修改成功', 
					icon: 'success',
					success: () => {
						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				})
				
			} catch (error) {
				uni.hideLoading()
				console.error('提交失败:', error)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.page-container {
	min-height: 100vh;
	background: #f5f5f5;
}

.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 1;
}

.product-section {
	margin-bottom: 30rpx;
}

.product-section:last-child {
	margin-bottom: 0;
}

.text-center {
	text-align: center;
}

.disabled {
	opacity: 0.6;
	cursor: not-allowed;
	pointer-events: none;
}
</style>
